package com.gf.user.service.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gf.base.type.Activity;
import com.gf.base.type.TicketType;
import com.gf.user.dao.TicketDao;
import com.gf.user.model.Ticket;
import com.gf.user.model.User;
import com.gf.user.service.TicketService;
import com.gf.user.service.UserBaseService;

/**
 * 
 * @author zhuguifeng
 * 
 */
@Transactional
@Service("ticketService")
public class TicketServiceImpl implements TicketService {

	private static Log logger = LogFactory.getLog(TicketServiceImpl.class);
	
	@Autowired
	private TicketDao ticketDao;
	
	@Autowired
	private UserBaseService userBaseService;
	

	// ticket的有效时间
	private static long TICKET_VALID_TIME = 24 * 60 * 60 * 1000;

	/**
	 * 返回: 无效-1;过期0;有效1
	 * 若是激活帐号：账号已激活2
	 */
	@Override
	public int isValid(String uuid) {
		Ticket ticket = ticketDao.queryByUuid(uuid);

		logger.info(ticket);
		if (ticket != null) {
			logger.info("用户："+ticket.getUserId()+" uuid:"+ticket.getUuid());
			//谇ticket用于激活帐号（用户多次点击激活URL,若激活提醒 用户）
			if(ticket.getTicketType().toString().equals(TicketType.ACTIVE.toString())){
				User user = userBaseService.getUserById(ticket.getUserId());
				if(!user.getActivity().toString().equals(Activity.INACTIVE.toString())){
					return 2;
				}
				//该ticket已经删除了 
				if(ticket.getActivity().toString().equals(Activity.DELETED.toString())){
					return 0;
				}
			}
			
			
			long now = System.currentTimeMillis();
			long creatTime = ticket.getCreatetime().getTime();

			if ((now - creatTime) <= TICKET_VALID_TIME) {
				return 1;
				// ticket已经过期，删除activity->deleted
			} else {
				ticketDao.updateActivity(ticket.getId(), Activity.DELETED);
				return 0;
			}

		} else {
			return -1;
		}

	}
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	@Override
	public long addFindPasswdTicket(long userId, String uuid) {
		return ticketDao.insert(userId, uuid, TicketType.FINDPASSWD);
	}
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	@Override
	public long addActiveTicket(long userId, String uuid) {
		return ticketDao.insert(userId, uuid, TicketType.ACTIVE);
	}
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	@Override
	public void deleteTicket(long id) {
		ticketDao.updateActivity(id, Activity.DELETED);
	}

	@Override
	public Ticket getTicket(long id) {
		return ticketDao.queryById(id);
	}
	@Override
	public Ticket getTicketByUUID(String uuid) {
		return ticketDao.queryByUuid(uuid);
	}

}
